<?php

namespace app\http\middleware;

class VerifyPower
{
    public function handle($request, \Closure $next)
    {
        if (!$request->_role) {
            return errJson('权限中间件必须存在角色关系');
        }
        $path = request()->path();
        $powerNode = app('powerNode');
        $where[] = ['node_path','=',$path];
        $flags = $powerNode->where($where)->column('status','id');

        $nodes = $request->_role->nodes->toArray();
        $nodeIds = array_column($nodes,'id');
        $step = 0;//无权限
        foreach ($flags as $id => $status){
            if (in_array($id,$nodeIds)){
                if ($status != 1){
                    $step = 2;//禁用
                }else{
                    $step = 1;//通行
                    break;
                }
            }
        }
        if ($step === 0){
            return errJson('无此权限');
        }
        if ($step === 2){
            return errJson('节点禁用');
        }
        return $next($request);
    }
}
